package pub.cleangao.mybatis.execution;

import lombok.Data;
import lombok.EqualsAndHashCode;
import pub.cleangao.mybatis.expression.WhereExpression;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


@EqualsAndHashCode(callSuper = true)
@Data
public class DeleteExecution extends AbstractExecution {

    /**
     * 开启删除流程
     *
     * @param table 表名
     * @return 当前执行体
     */
    public static DeleteExecution startDelete(String table) {
        DeleteExecution deleteExecution = new DeleteExecution();
        deleteExecution.setTable(table);
        deleteExecution.setWhereExpressionList(new ArrayList<>());
        return deleteExecution;
    }

    /**
     * 待删除的目标表
     */
    private String table;


    private List<WhereExpression> whereExpressionList;

    @Override
    public Object runInDataSource(Connection connection) throws SQLException {
        if (whereExpressionList == null || whereExpressionList.isEmpty()) {
            throw new SQLException("where condition is required for DELETE operation.");
        }
        whereExpressionList.sort((o1, o2) -> {
            return o1.index() - o2.index();
        });
        StringBuilder sql = new StringBuilder();
        sql.append("DELETE FROM ");
        sql.append(table);
        sql.append(" WHERE ");
        PreparedStatement statement = connection.prepareStatement(generateWhereClause(sql,whereExpressionList));
        return statement.executeUpdate();
    }


}
